/**
 * 
 */
package org.shanktech.tshare.binlogsync.process.parser;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.shanktech.tshare.binlogsync.model.binlog.BinlogData;
import org.shanktech.tshare.binlogsync.model.binlog.UpdateBinlogData;
import org.shanktech.tshare.binlogsync.process.BinlogdataParser;
import org.shanktech.tshare.binlogsync.util.Constant;
import org.shanktech.tshare.binlogsync.util.SpringUtil;
import org.springframework.jdbc.core.JdbcTemplate;

import com.google.code.or.common.glossary.Column;

public class RowModelParser implements BinlogdataParser {

  private JdbcTemplate version1JdbcTemplate;

  public RowModelParser() {
    version1JdbcTemplate =
        (JdbcTemplate) SpringUtil.getBean("version1JdbcTemplate");
  }

  @Override
  public Object parser(BinlogData binlogData, ObjectParser objectParser) {

    Map<String, Object[]> result = getColumnAndValue(binlogData.getColumnList(),
        binlogData.getDatabaseName(), binlogData.getTableName());

    if (Constant.SqlDML.UPDATE.getValue()
        .equalsIgnoreCase(binlogData.getType())) {
      Map<String, Object> resultObject = new HashMap<>();
      resultObject.put("afterObject", objectParser.parser((String[]) result.get("name"),
          result.get("value")));
      
      UpdateBinlogData updateBinlogData = (UpdateBinlogData)binlogData;
      
      // beforColumn解析
      result = getColumnAndValue(updateBinlogData.getColsBefore(),
          binlogData.getDatabaseName(), binlogData.getTableName());
      
      resultObject.put("beforObject", objectParser.parser((String[]) result.get("name"),
          result.get("value")));
      
      return resultObject;
      
    }
    
    return objectParser.parser((String[]) result.get("name"),
        result.get("value"));
  }

  private Map<String, Object[]> getColumnAndValue(
      final List<Column> columnList,String databaseName, String tableName) {
    Map<String, Object[]> resultMap = new HashMap<>();
    resultMap.put("name", getColumnNames(databaseName, tableName));
    List<Object> valueList = new ArrayList<>(); 
    for (Column column : columnList) {
      valueList.add(column.toString());
    }
    resultMap.put("value", valueList.toArray());
    return resultMap;
  }

  private String[] getColumnNames(String databaseName, String tableName) {
    List<String> columnList = new ArrayList<>();
    try {
      ResultSet columnSet = version1JdbcTemplate.getDataSource().getConnection()
          .getMetaData().getColumns(databaseName, null, tableName, null);

      while (columnSet.next()) {
        columnList.add(columnSet.getString("COLUMN_NAME"));
      }
    } catch (SQLException e) {
    }

    String[] array = new String[columnList.size()];
    return columnList.toArray(array);
  }

}
